/*
 * @Date: 2023-11-08 11:01:26
 * @LastEditors: lyx
 * @LastEditTime: 2023-12-12 15:01:11
 * @FilePath: \sup-mimi-program-server\utils\mongo-crud\crud-query.decorator.ts
 * @Description:
 */
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { Request } from 'express';
import { get } from 'lodash';
import { isQueryAll } from '.';

export const CrudQuery = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const req: Request = ctx.switchToHttp().getRequest();
    try {
      console.log('CrudQuery params111');
      const params = req?.body || {};
      console.log('CrudQuery params', params);

      let [page, limit] = get(params, 'requestBase.page', '1-10')
        ?.split('-')
        .map((item) => parseInt(item)) ?? [1, 10];
      const where = get(params, 'data.where', {});
      let skip = get(params, 'requestBase.skip', 0);
      const populate = get(params, 'requestBase.populate', undefined);
      const sort = get(params, 'requestBase.sort', undefined);
      const collation = get(params, 'requestBase.collation', undefined);

      if (skip < 1) {
        skip = (page - 1) * limit;
      }

      if (isQueryAll(page, limit)) {
        // 兼容 0-0 查询所有
        skip = 0;
        page = 1;
      }
      return {
        page,
        limit,
        where,
        skip,
        populate,
        sort,
        collation,
      };
    } catch (e) {
      return {};
    }
  },
);
